<?php 
putenv('DJ_LOGDIR='      . LOGDIR);


// connects to a db-server if not yet connected
//***** la conexion entre el servidor judgedaemon y msql para la segunda db se establece cada que judgedaemon esta up, pero SOLO SE UTILIZA si el contest es tipo post. la conexion queda open//*****

////esta lib aloja una serie de funciones que son utiles para actuar sobre los datos de db2, son usadas por
//el judgedaemon

function connect_db2($database, $host, $user, $pass)
{
	//global $connection2;
	$con = 'mysql_connect';
	if(!function_exists($con)) {
		throw new RuntimeException("PHP database module missing "
			   . "(no such function: '$con')");
	}

	$connection2 = @$con($host, $user, $pass);

	if(!$connection2) {
		throw new RuntimeException("Could not connect to database server "
			   . "(host=$host,user=$user,password="
			   . str_repeat('*', strlen($pass)) . ")");
	}

	if(!mysql_select_db($database, $connection2)) {
		throw new RuntimeException("Could not select database '"
			   . $database . "': " . mysql_error($connection2));
	}

	return $connection2;
}



## busca el nombre del usuario y llama la funcion para que cree la conexion
function setup_database_connection_domjudge2($privlevel)
{
	//global $connection2, $db;
	$credfile = ETCDIR . '/dbpasswords_db2.secret';
	$credentials = @file($credfile);

	if (!$credentials) {
		user_error("Cannot read database credentials file " . $credfile,
			E_USER_ERROR);
		exit();
	}


	foreach ($credentials as $credential) {
		if ( $credential{0} == '#' ) continue;
		list ($priv, $host, $db, $user, $pass) =
			explode(':', trim($credential));
		if ($priv != $privlevel) continue;

		//$conexion = connect_db2($db."2", $host, $user."w", $pass);	
//		$db2 = $db."2";
		$conexion2 = connect_db2($db , $host, $user, $pass);	

		break;
	}
	//##logmsg(LOG_NOTICE, "db: $db");
	if (!$conexion2) {
		user_error(sprintf("Privilege level '%s' not supported",
			$privlevel), E_USER_ERROR);
		exit();
	}else{
		return $conexion2;
	}	
}

function insert_sc_db2( $cid, $teamid, $probid, $submittime, $source, $language)
{
	//global $connection2;
	$db2 = "domjudge2";

	$conn2  = setup_database_connection_domjudge2('juryz');
	logmsg(LOG_NOTICE, "Conectando a db2:  $db2");

	$source = addslashes($source);

	//comprobar si el team ya ha sometido la solucion
	$query = "SELECT `scid` FROM `solution_sc` WHERE `cid`= '$cid' AND `teamid`='$teamid' AND `probid`='$probid' ";
	mysql_select_db($db2 , $conn2);
	$trans = mysql_query($query ,$conn2);

	if($trans)
	{
		$n_sc = mysql_num_rows($trans);
	}else{
		throw new RuntimeException("SQL syntax-error, ". "Error " .
			mysql_error($conn2) . ", query: '$trans'");
	}
	
	if($n_sc == 0)
	{
		$q = "INSERT INTO `solution_sc` (`cid`,`teamid`,`probid`,`submittime`,`sourcecode`,`langid`)
			 values('$cid','$teamid', '$probid','$submittime','$source', '$language')";
		//mysql_select_db($db2 , $conn2);
		$res = mysql_query($q, $conn2);
		///capturar excepciones 
		if($res)
		{
			logmsg(LOG_NOTICE, "Se ha insertado el sc en la db2:  $db2");	
		}else{
			throw new RuntimeException("SQL syntax-error, ". "Error " .
			 	mysql_error($conn2) . ", query: '$q'");
		}
	}else{
		logmsg(LOG_INFO, "Ya había sometido el source code");
	}
	///cerrar conexion
	mysql_close($conn2);
	logmsg(LOG_NOTICE, "Cerrando conexion con db2:  $db2");
}

// función para sumar minutos 
/*function add_date($givendate,$minus) 
{
$cd = strtotime($givendate);
$newdate = date('Y-m-d H:i:s', mktime(date('H',$cd),
    			date('i',$cd)+$minus, date('s',$cd), date('m',$cd),
    			date('d',$cd), date('Y',$cd)));
return $newdate;
}*/

//funcion para insertar los casos de prueba en testcase_past
function inser_testcase($testcases)
{
	global $connection2, $db2;
	$in = "INSERT INTO `testcase_past` (`testcaseid`, `input`,`output`,`probid`,`rank`,`description`) 	values('".$testcases['testcaseid']."','".$testcases['input']."','".$testcases['output']."','".
	$testcases['probid']."','".$testcases['rank']."','".$testcases['description']."')";
	mysql_select_db($db, $connection2);
	$res = mysql_query($in, $connection2);
	if(!$res)
	{
		throw new RuntimeException("SQL syntax-error, ". "Error " .
			mysql_error($connection2) .", query: '$in'");
	}		
}
//obtener testcases asociados a un problema
function get_testcase($probid)
{	
	global $connection2;
	$query = "SELECT `testcaseid`, `input`, `output`,`probid`,`rank`,`description` 
			FROM testcase WHERE `probid`='$probid'";

	$res = mysql_query($query ,$connection2);
	if($res)
	{
		$respuesta = array();
		$nrows = mysql_num_rows($res);
		$respuesta[0] = $nrows;

		for($i=0; $i<$nrows; $i++)
		{
			$datos = mysql_fetch_array($res, MYSQL_BOTH);
			$respuesta[$i+1] = $datos;
		}
		return $respuesta;
	}else{
		throw new RuntimeException("SQL syntax-error, ". "Error " .
				mysql_error($connection2) . ", query: '$query'");
	}	
}

//obtener los problemas asociados a un contest
function get_problems($cid)
{
	global $connection2;
	$query = "SELECT `probid` FROM problem WHERE cid='$cid'";
	$res = mysql_query($query ,$connection2);
	if($res)
	{
		$respuesta = array();
		$nrows = mysql_num_rows($res);
		$respuesta[0] = $nrows;

		for($i=0; $i<$nrows; $i++)
		{
			$datos = mysql_fetch_array($res, MYSQL_BOTH);
			$respuesta[$i+1] = $datos;
		}
		return $respuesta;
	}else{
		throw new RuntimeException("SQL syntax-error, ". "Error " .
			mysql_error($connection2) . ", query: '$query'");
	}
}

//hacer el backup de testcases correspondientes a contest tipo inner pasados
function backup_testcases($cid)
{
	$problems = get_problems($cid);

	for( $i=1; $i<=$problems[0]; $i++)
	{
		$testcases[$i] = get_testcase($problems[$i][0]);
	}

	for($i=1; $i<=count($testcases); $i++)
	{
		for($j=1; $j<=$testcases[$i][0]; $j++)
		{
			inser_testcase($testcases[$i][$j]);
			
		}
	}
}


?>
